import {Net, WithFormUrlEncodedBody, WithHttpMethod, WithoutToken} from "mvx-foundation";
import {RegisterAutoLogin as fRegisterAutoLogin} from "mvx-uni-app";

class Body {
  public userId:string|null=null;
  public token:string|null=null;
  public unionId:string|null=null;
  public openId:string|null=null;
}

class Response {
  public body:Body = new Body();
}

export  function RegisterAutoLogin(net:Net) {
  const login = ():Promise<string|undefined> => {
    return new Promise(resolve => {
      uni.login({
        success:(ret) => {
          resolve(ret.code);
        },
        fail:() => {
          resolve(undefined);
        }
      });
    });
  };
  fRegisterAutoLogin<Response>(net, '/customer/v2/login/code2Session', async ()=> {
    let code = await login();
    return {code:code, wxMaAppid:uni.getAccountInfoSync().miniProgram.appId};
  }, Response, (ret) => {
    return {uid:ret.body.userId!, token:ret.body.token!};
  }, async (err) => {
      await uni.showModal({title:"登录失败("+ err.message +")", showCancel:false});
  },  WithFormUrlEncodedBody(), WithoutToken(), WithHttpMethod("GET"));
}